<?php

namespace App\Http\Controllers\Client\Member;

use App\Models\Member\Member;
use App\Services\Sms\CaptchaService;
use Illuminate\Http\Request;
use App\Http\Controllers\RootController as Controller;
use Illuminate\Support\Facades\DB;

class UpdatePwdController extends Controller
{
    public function handle(Request $request, Member $model)
    {
        /******参数 start******/
        $param['mobile'] = (string)$request->input('mobile', '');
        $param['code'] = (string)$request->input('code', '');
        $param['pwd'] = trim($request->input('pwd', ''));
        $param['two_pwd'] = trim($request->input('two_pwd', ''));

        $rules    = [
            'mobile'  => 'required',
            'code' => 'required',
            'pwd' => 'required',
            'two_pwd' => 'required',
        ];
        $messages = [
            'mobile.required'                    => '请输入手机号',
            'code.required'                    => '请输入验证码',
            'pwd.required'                   => '请输入密码',
            'two_pwd.required'                   => '请输入确认密码',
        ];

        if (true !== ($error = $this->validator($param, $rules, $messages)))
        {
            return $this->failure($error, 'VALIDATION_FAIL');
        }

        if($param['pwd'] != $param['two_pwd']) return $this->failure('新密码和确认密码不一致！');


        // 短信验证码
        if ('0000' != $param['code']) // 调试
        {
            try{
                CaptchaService::verify($param['mobile'], $param['code']);
            }catch(\Exception $e){
                return $this->failure($e->getMessage(), 'VALIDATION_FAIL');
            }
        }

        try
        {
            DB::beginTransaction();

            $member = $model->find($this->id('member'));
            $member->update([
                'pwd' => md5($param['pwd'])
            ]);


            DB::commit();
        }
        catch (\Exception $e)
        {
            DB::rollBack();
            return $this->failure($e->getMessage(), 'E_DB');
        }

        return $this->success();
    }
}
